<?php
// +----------------------------------------------------------------------
// | View 视图服务
// +----------------------------------------------------------------------
// | * 视图层
// | * 1.查询所有关联表的字段
// | * 2.处理字段（可显示、可编辑、可排序、可分组、可过滤）、还要通过临时字段、字段权限进行判断，组装出view需要的字段
// | * 3.组装view视图的表格列
// +----------------------------------------------------------------------
// | 错误编码头 231xxx
// +----------------------------------------------------------------------

namespace common\service;

use common\model\MessageTaskConfirmModel;
use support\SingletonTrait;

class MessageTaskConfirmService
{
    use SingletonTrait;

    /**
     * 列表
     * @param     $data
     * @param int $tenantId
     * @return array|mixed|string
     */
    public function list($data, int $tenantId)
    {
        $param = $data['param'] ?? [];
        $filter = $param['filter'] ?? [];
        $messageTaskConfirmLinkStepCategory = $filter['message_task_confirm_link_step_category'] ?? [];
        unset($filter['message_task_confirm_link_step_category']);
        $page = $data['page'] ?? [1, C('default_page_total')];
        if (!empty($messageTaskConfirmLinkStepCategory)) {
            sort($messageTaskConfirmLinkStepCategory);
            $messageTaskConfirmLinkStepCategory = join(',', $messageTaskConfirmLinkStepCategory);
            $filter['message_task_confirm.link_step_category'] = $messageTaskConfirmLinkStepCategory;
        }
        $fields = [
            'message_task_confirm.id',
            'if(link_module_code = "task", link_module_code, entity_module.code) as link_module_code', // 任务 or 实体的实际所属模块
            'link_module_code as link_module_code_category', // 任务 or 实体
            'link_id',
            'link_step_category',
            'confirm',
            'confirm_user_id',
            'source_type',
            'message_task_confirm.remark',
            'message_task_confirm.project_id',
            'entity.name               as entity_entity_name',
            'entity.initial_episode_code as entity_initial_episode_code',
            'entity.showings_number as entity_showings_number',
            'entity.json                       as entity_json',
            "JSON_UNQUOTE(JSON_EXTRACT(entity.json,'$.asset_grade'))  as entity_entity_design_grade",
            "JSON_UNQUOTE(JSON_EXTRACT(entity.json,'$.asset_category')) as entity_entity_design_category",
            "task.entity_name                  as task_entity_name",
            "task.initial_episode_code         as task_entity_initial_episode_code",
            "task.showings_number              as task_showings_number",
            "task.step_category_name           as task_step_category_name",
            "task.step_name                    as task_step_name",
            "task.grade                        as task_entity_design_grade",
            "task.category                     as task_entity_design_category",
            "task.executor",
            "task.task_id as task_id"
        ];

        $filter = [$filter, [
            'link_module_code' => ['in', ['task', 'version', 'entity']]
        ]];
        $count = model(MessageTaskConfirmModel::class)
            ->join("left join (select task_tmp.id as task_id,entity.name as entity_name,entity.initial_episode_code,entity.showings_number,step_category.name as step_category_name,step.name as step_name,JSON_UNQUOTE(JSON_EXTRACT(entity.json, CONCAT('$.', module.code, '_grade'))) as grade,JSON_UNQUOTE(JSON_EXTRACT(entity.json, CONCAT('$.', module.code, '_category'))) as category,step_id,executor from task task_tmp join entity on task_tmp.entity_id = entity.id join step_category on step_category.id = task_tmp.step_category_id join step on step.id = task_tmp.step_id join module on module.id = entity.module_id) as task on task.task_id = message_task_confirm.link_id and link_module_code = 'task'")
            ->join("entity on entity.id = message_task_confirm.link_id and message_task_confirm.link_module_code IN ('asset', 'shot', 'level', 'entity')", 'LEFT')
            ->join("module entity_module on entity_module.id = entity.module_id", 'LEFT')
            ->where(['message_task_confirm.tenant_id' => $tenantId])
            ->where($filter)
            ->count();
        if (empty($count)) {
            return ['rows' => [], 'total' => 0];
        }
        $list = model(MessageTaskConfirmModel::class)
            ->field($fields)
            ->join("left join (select task_tmp.id as task_id,entity.name as entity_name,entity.initial_episode_code,entity.showings_number,step_category.name as step_category_name,step.name as step_name,JSON_UNQUOTE(JSON_EXTRACT(entity.json, CONCAT('$.', module.code, '_grade'))) as grade,JSON_UNQUOTE(JSON_EXTRACT(entity.json, CONCAT('$.', module.code, '_category'))) as category,step_id,executor from task task_tmp join entity on task_tmp.entity_id = entity.id join step_category on step_category.id = task_tmp.step_category_id join step on step.id = task_tmp.step_id join module on module.id = entity.module_id) as task on task.task_id = message_task_confirm.link_id and link_module_code = 'task'")
            ->join("entity on entity.id = message_task_confirm.link_id and message_task_confirm.link_module_code IN ('asset', 'shot', 'level', 'entity')", 'LEFT')
            ->join("module entity_module on entity_module.id = entity.module_id", 'LEFT')
            ->where(['message_task_confirm.tenant_id' => $tenantId])
            ->where($filter)
            ->page(...$page)
            ->select();
        if (empty($list)) {
            return [];
        }
        foreach ($list as &$item) {
            $entityJson = json_decode($item['entity_json'], true);
            $entityParent = [];
            switch ($item['link_module_code']) {
                case 'task':
                    break;
                case 'sequence':
                    $entityParent = ['entity_parent_id' => $item['link_id']];
                    break;
                case 'shot':
                    $entityParent = ['entity_parent_id' => $entityJson[$item['link_module_code'] . '_storyboard'] ?? $item['link_id']];
                    break;
                default:
                    $entityParent = ['entity_parent_id' => $entityJson[$item['link_module_code'] . '_design'] ?? $item['link_id']];
            }
            $item = array_merge($item, [
                'initial_episode_code' => (!empty($item['task_entity_initial_episode_code'])) ? $item['task_entity_initial_episode_code'] : $item['entity_initial_episode_code'],
                'showings_number' => (!empty($item['task_showings_number'])) ? $item['task_showings_number'] : $item['entity_showings_number'],
            ], $entityParent);
            unset($item['entity_json']);
        }
        return ['rows' => $list, 'total' => $count];
    }
}


